<template>
  <div :class="$style.channelRelAdd">
    <Button type="primary" @click="showClick">{{ text }}</Button>
    <el-dialog
      :visible.sync="visible"
      destroy-on-close
      :title="title"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="closeDialog"
      @opened="initFormData"
    >
      <div>
        <el-form
          ref="form"
          :model="formData"
          :rules="formRules"
          label-width="110px"
        >
          <el-form-item prop="businessType" label="一级业务类型">
            <CustomDictSelect
              dict-type-code="FIRST_LEVEL_BUSINESS_TYPE"
              placeholder="请选择一级业务类型"
              bind-name="dictName"
              bind-value="dictCode"
              filterable
              :remote="false"
              :echo-value.sync="formData.businessType"
              :echo-name.sync="formData.businessTypeName"
            ></CustomDictSelect>
          </el-form-item>
          <el-form-item prop="businessTypeTwo" label="二级业务类型">
            <CustomDictSelect
              dict-type-code="SECOND_LEVEL_BUSINESS_TYPE"
              placeholder="请选择二级业务类型"
              bind-name="dictName"
              bind-value="dictCode"
              filterable
              :remote="false"
              :echo-value.sync="formData.businessTypeTwo"
              :echo-name.sync="formData.businessTypeTwoName"
            ></CustomDictSelect>
          </el-form-item>
          <el-form-item prop="channel" label="购买渠道">
            <CustomDictSelect
              dict-type-code="PURCHASE_CHANNEL"
              placeholder="请选择购买渠道"
              bind-name="dictName"
              bind-value="dictCode"
              filterable
              :remote="false"
              :echo-value.sync="formData.channel"
              :echo-name.sync="formData.channelName"
            ></CustomDictSelect>
            <!-- @on-change="channelChange" -->
          </el-form-item>
          <el-form-item label="时效" prop="prescription">
            <el-input v-model="formData.prescription" clearable placeholder="请输入时效">
              <template slot="append">小时</template>
            </el-input>
          </el-form-item>
          <el-form-item align="right">
            <Button @click="closeDialog">取消</Button>
            <Button type="primary" :loading="loading" @click="submitHandle">确定</Button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Button from '@/components/Button'
import CustomDictSelect from '@/components/CustomDictSelect'
import { saveChannelBusinessRel } from '@/api/ChannelBusinessRel'
export default {
  name: 'ChannelRelAdd',
  components: {
    Button,
    CustomDictSelect
  },
  props: {
    row: {
      type: Object,
      default: () => ({})
    },
    text: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    const validatorPrescription = (r, v, c) => {
      if (/^\d+|\d+\.\d+$/.test(v) && Number.parseFloat(v) <= 0) {
        c(new Error('时效必须大于0'))
      } else if (/^\d+|\d+\.\d+$/.test(v)) {
        c()
      } else {
        c(new Error('时效必填且只能是数字'))
      }
    }
    return {
      visible: false,
      loading: false,
      formData: {
        businessType: '',
        businessTypeName: '',
        businessTypeTwo: '',
        businessTypeTwoName: '',
        channel: '', // 责任部门编码
        channelName: '', // 责任部门
        prescription: '' // 时效
      },
      formRules: {
        businessType: [
          { required: true, message: '一级业务类型不能为空', trigger: 'change' }
        ],
        businessTypeTwo: [
          { required: true, message: '二级业务类型不能为空', trigger: 'change' }
        ],
        channel: [
          { required: true, message: '购买渠道不能为空', trigger: 'change' }
        ],
        prescription: [
          { required: true, validator: validatorPrescription, trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    isEdit() {
      return Object.keys(this.row).length > 0
    }
  },
  methods: {
    showClick() {
      if (this.text === '编辑' && Object.keys(this.row).length === 0) {
        this.$message({
          message: '请选择需编辑项',
          type: 'warning'
        })
        return
      }
      // Object.assign(this.formRules, { businessType: [], businessTypeTwo: [] })
      // setTimeout(() => { this.$refs.form.validateField(['businessType', 'businessTypeTwo']) }, 0)
      this.visible = true
    },
    // TODO:废弃 验证销售管理三部、电商运营部是否必填
    channelChange() {
      this.$refs['form'].clearValidate()
      if (this.formData.channelName === '销售管理三部' || this.formData.channelName === '电商运营部') {
        Object.assign(
          this.formRules,
          {
            businessType: [
              { required: true, message: '一级业务类型不能为空', trigger: 'change' }
            ],
            businessTypeTwo: [
              { required: true, message: '二级业务类型不能为空', trigger: 'change' }
            ]
          })

        setTimeout(() => { this.$refs.form.validateField(['businessType', 'businessTypeTwo']) }, 0)
      } else {
        Object.assign(this.formRules, { businessType: [], businessTypeTwo: [] })
        setTimeout(() => { this.$refs.form.validateField(['businessType', 'businessTypeTwo']) }, 0)
      }
    },
    // 增加、修改
    submitHandle() {
      if (this.loading) return
      this.$refs.form.validate().then(() => {
        this.loading = true
        const params = { ...this.formData }
        if (this.isEdit) {
          params.id = this.row.id
        }
        saveChannelBusinessRel(params).then(res => {
          this.loading = false
          if (res.success === 1) {
            this.$message.success('保存成功')
            this.$emit('on-success', !this.isEdit)
            this.closeDialog()
          }
        }).catch(() => {
          this.loading = false
        })
      })
    },
    clearForm() {
      for (const key of Object.keys(this.formData)) {
        this.$set(this.formData, key, '')
      }
      this.$refs.form && this.$refs.form.clearValidate()
      this.$refs.form && this.$refs.form.resetFields()
    },
    closeDialog() {
      this.clearForm()
      this.visible = false
    },
    initFormData() {
      for (const key of Object.keys(this.formData)) {
        this.$set(this.formData, key, '')
      }
      if (this.isEdit) {
        const row = { ...this.row }
        if (!row['businessType'] || !row['businessTypeName']) {
          this.$set(row, 'businessType', '')
          this.$set(row, 'businessTypeName', '')
        }
        if (!row['businessTypeTwo'] || !row['businessTypeTwoName']) {
          this.$set(row, 'businessTypeTwo', '')
          this.$set(row, 'businessTypeTwoName', '')
        }
        for (const key of Object.keys(this.formData)) {
          this.$set(this.formData, key, row[key])
        }
        /* this.$nextTick(() => {
          this.channelChange()
        }) */
      }
    }
  }
}
</script>
<style lang="scss" module>
.channelRelAdd {

}
</style>
